package com.xjscrm.console.chat;

import com.xjscrm.console.chat.handler.WebSocketServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * @author mingyang.chen create in 2024/3/14 16:22
 */
@Component
@Slf4j
public class ChatWebsocketServer {

    @Autowired
    WebSocketServerHandler webSocketServerHandler;


    @PostConstruct
    public void start() throws Exception {
        new Thread(() -> {
            // 创建主线程组
            EventLoopGroup bossGroup = new NioEventLoopGroup();
            // 创建工作线程组
            EventLoopGroup workerGroup = new NioEventLoopGroup();

            try {
                // 创建ServerBootstrap
                ServerBootstrap serverBootstrap = new ServerBootstrap();
                serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new HttpServerCodec());
                        ch.pipeline().addLast(new HttpObjectAggregator(65536));
                        ch.pipeline().addLast(new WebSocketServerProtocolHandler("/websocket"));
                        ch.pipeline().addLast(new IdleStateHandler(70, 70, 70));
                        ch.pipeline().addLast(webSocketServerHandler);
                    }
                }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);

                log.info("WebSocket Server 启动...");

                try {
                    // 绑定端口并开始接收连接
                    Channel channel = serverBootstrap.bind(9751).sync().channel();
                    // 等待服务器Socket关闭
                    channel.closeFuture().sync();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            } finally {
                // 释放线程资源
                bossGroup.shutdownGracefully();
                workerGroup.shutdownGracefully();
            }
        }).start();
    }
}
